package com.czhoujunlv.drug;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;
import androidx.constraintlayout.widget.ConstraintLayout;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import android.annotation.SuppressLint;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.alipay.sdk.app.EnvUtils;
import com.alipay.sdk.app.PayTask;
import com.bumptech.glide.Glide;
import com.czhoujunlv.drug.Bean.Dingdan;
import com.czhoujunlv.drug.Bean.Dingdan2;
import com.czhoujunlv.drug.DBManager.Manager;
import com.czhoujunlv.drug.fragment.BuyFragment;
import com.czhoujunlv.drug.fragment.HeadFragment;
import com.czhoujunlv.drug.pay.PayResult;
import com.czhoujunlv.drug.pay.SignUtils;
import com.google.gson.Gson;

import org.greenrobot.eventbus.EventBus;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Random;

import okhttp3.MediaType;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

public class dingdan extends AppCompatActivity {

    public static final String PARTNER = "2088621954994414";

    // 商户收款账号
    public static final String SELLER = "lvuken0566@sandbox.com";

    // 商户私钥，pkcs8格式
    public static final String RSA_PRIVATE = "MIIEvQIBADANBgkqhkiG9w0BAQEFAASCBKcwggSjAgEAAoIBAQCP90CIBryaAl/qC+Aa1YR9KIKPQCwM6QU/21WXHw4xsacmc6IH3VkLJne00foWVm4fIBXHReCiDhaROpHzIKvC0oge04L5jsPolftJ3oDgnyHu12PQ0GQYf16GjlCbPV80/q7wyv0jHtG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UD6o8QZGiEvhB/+vysdBEA0cTqk0ZcYIYUQONqRTgGbiFyARA2GYOryL3C8K8e/I9LfGTKnrlx53BDbdDjhvFy1m0gcECieuNKETVVa0+4yY7I1hyCdteGUWMvy1jsJ4OnqGrAxfTz5solRjxs+FroMeYZK6uFpF37Z7j40CgYEAnzOQYpc32au9PnZ2HoRBbwT8heKfV4sV5KM0Bt+iQAuWOqZqd11QvQkSu9LOtnRiimLpGsNUGIv69IcyxtShAx511nsU6CxFskgYHlR5E4Zpa+vgxFmRa9pMM9vw4qOwgsBtd7B3RLliEgOOIwaRpgXuzB1njyZ3A6BmmmAAFgo=";
    private static final int SDK_PAY_FLAG = 1;

    List<Dingdan> list = new ArrayList<>();
    List<Dingdan2> list2 = new ArrayList<>();
    TextView price1,address,name,tel;
    ImageView back;
    RecyclerView item;
    ConstraintLayout submit;
    private String json;

    @SuppressLint("HandlerLeak")
    private Handler mHandler = new Handler() {
        private Map<String,String> map;

        @SuppressWarnings("unused")
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case SDK_PAY_FLAG: {
                    PayResult payResult = new PayResult((String)msg.obj);
                    /**
                     * 同步返回的结果必须放置到服务端进行验证（验证的规则请看https://doc.open.alipay.com/doc2/
                     * detail.htm?spm=0.0.0.0.xdvAU6&treeId=59&articleId=103665&
                     * docType=1) 建议商户依赖异步通知
                     */
                    String resultInfo = payResult.getResult();// 同步返回需要验证的信息

                    String resultStatus = payResult.getResultStatus();
                    // 判断resultStatus 为“9000”则代表支付成功，具体状态码代表含义可参考接口文档
                    if (TextUtils.equals(resultStatus, "9000")) {
                        Toast.makeText(dingdan.this, "支付成功", Toast.LENGTH_SHORT).show();
                    } else {
                        // 判断resultStatus 为非"9000"则代表可能支付失败
                        // "8000"代表支付结果因为支付渠道原因或者系统原因还在等待支付结果确认，最终交易是否成功以服务端异步通知为准（小概率状态）
                        if (TextUtils.equals(resultStatus, "8000")) {
                            Toast.makeText(dingdan.this, "支付结果确认中", Toast.LENGTH_SHORT).show();

                        } else {
                            // 其他值就可以判断为支付失败，包括用户主动取消支付，或者系统返回的错误
                            Toast.makeText(dingdan.this, "支付失败", Toast.LENGTH_SHORT).show();

                        }
                    }
                    break;
                }
                default:
                    break;
            }
        }

    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {

        EnvUtils.setEnv(EnvUtils.EnvEnum.SANDBOX);
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_dingdan);

        init();

        Intent intent = getIntent();
        list.clear();
        list = Manager.queryAllDrug();
        Manager.deleteDrug();
        String num = intent.getStringExtra("number");

        for(int i =0 ;i<list.size();i++){
            Dingdan2 dingdan2 = new Dingdan2();
            dingdan2.address = address.getText().toString();
            dingdan2.businessId = list.get(i).businessId;
            dingdan2.buyId = 1;
            dingdan2.buyName = name.getText().toString();
            dingdan2.buyTelephone = tel.getText().toString();
            dingdan2.goodId = list.get(i).goodid;
            dingdan2.number = list.get(i).num;
            dingdan2.saleMoney = list.get(i).salemoney;
            dingdan2.orderStatus = "0";

            list2.add(dingdan2);
        }


        item.setAdapter(new MyAdapter4());//RecyclerView添加适配器
        item.setLayoutManager(new LinearLayoutManager(dingdan.this));
        price1.setText(intent.getStringExtra("price"));

        back.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                EventBus.getDefault().post("昵称123");
                for(int i=0;i<list2.size();i++){
                    list2.get(i).orderStatus = "0";//未付款
                }
                Gson gson = new Gson();
                json = gson.toJson(list2);
                Log.i("List转为json",json);
                Thread thread = new Thread(){
                    @Override
                    public void run() {
                        super.run();
                        try {
                            String s = post("http://192.168.43.138:8080/index/addOrder",json);
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    }
                };
                thread.start();
                finish();
            }
        });
        submit.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                EventBus.getDefault().post("fragment send3");
                for(int i=0;i<list2.size();i++){
                    list2.get(i).orderStatus = "1";//已付款
                }
                Gson gson = new Gson();
                json = gson.toJson(list2);
                Log.i("List转为json",json);
                Thread thread = new Thread(){
                    @Override
                    public void run() {
                        super.run();
                        try {
                            String s = post("http://192.168.43.138:8080/index/addOrder",json);
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    }
                };
                thread.start();
                testAlipay();
                //finish();
            }
        });
    }
    public void testAlipay() {
        if (TextUtils.isEmpty(PARTNER) || TextUtils.isEmpty(RSA_PRIVATE) || TextUtils.isEmpty(SELLER)) {
            new AlertDialog.Builder(this).setTitle("警告").setMessage("需要配置PARTNER | RSA_PRIVATE| SELLER")
                    .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                        public void onClick(DialogInterface dialoginterface, int i) {
                            //
                            finish();
                        }
                    }).show();
            return;
        }

        String orderInfo = getOrderInfo("测试的商品", "该测试商品的详细描述", "0.01");

/**
 * 特别注意，这里的签名逻辑需要放在服务端，切勿将私钥泄露在代码中！
 */
        String sign = sign(orderInfo);
        try {
            /**
             * 仅需对sign 做URL编码
             */
            sign = URLEncoder.encode(sign, "UTF-8");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }

/**
 * 完整的符合支付宝参数规范的订单信息
 */
        final String payInfo = orderInfo + "&sign=\"" + sign + "\"&" + getSignType();

        Runnable payRunnable = new Runnable() {

            @Override
            public void run() {
                // 构造PayTask 对象
                PayTask alipay = new PayTask(dingdan.this);
                // 调用支付接口，获取支付结果
                String result = alipay.pay(payInfo, false);

                Message msg = new Message();
                msg.what = SDK_PAY_FLAG;
                msg.obj = result;
                Log.i("支付宝：：",String.valueOf(msg.obj));
                mHandler.sendMessage(msg);
            }
        };

// 必须异步调用
        Thread payThread = new Thread(payRunnable);
        payThread.start();
    }
    /**
     * create the order info. 创建订单信息
     */
    private String getOrderInfo(String subject, String body, String price) {

        // 签约合作者身份ID
        String orderInfo = "partner=" + "\"" + PARTNER + "\"";

        // 签约卖家支付宝账号
        orderInfo += "&seller_id=" + "\"" + SELLER + "\"";

        // 商户网站唯一订单号
        orderInfo += "&out_trade_no=" + "\"" + getOutTradeNo() + "\"";

        // 商品名称
        orderInfo += "&subject=" + "\"" + subject + "\"";

        // 商品详情
        orderInfo += "&body=" + "\"" + body + "\"";

        // 商品金额
        orderInfo += "&total_fee=" + "\"" + price + "\"";

        // 服务器异步通知页面路径
        orderInfo += "&notify_url=" + "\"" + "http://notify.msp.hk/notify.htm" + "\"";

        // 服务接口名称， 固定值
        orderInfo += "&service=\"mobile.securitypay.pay\"";

        // 支付类型， 固定值
        orderInfo += "&payment_type=\"1\"";

        // 参数编码， 固定值
        orderInfo += "&_input_charset=\"utf-8\"";

        // 设置未付款交易的超时时间
        // 默认30分钟，一旦超时，该笔交易就会自动被关闭。
        // 取值范围：1m～15d。
        // m-分钟，h-小时，d-天，1c-当天（无论交易何时创建，都在0点关闭）。
        // 该参数数值不接受小数点，如1.5h，可转换为90m。
        orderInfo += "&it_b_pay=\"30m\"";

        // extern_token为经过快登授权获取到的alipay_open_id,带上此参数用户将使用授权的账户进行支付
        // orderInfo += "&extern_token=" + "\"" + extern_token + "\"";

        // 支付宝处理完请求后，当前页面跳转到商户指定页面的路径，可空
        orderInfo += "&return_url=\"m.alipay.com\"";

        // 调用银行卡支付，需配置此参数，参与签名， 固定值 （需要签约《无线银行卡快捷支付》才能使用）
        // orderInfo += "&paymethod=\"expressGateway\"";

        return orderInfo;
    }
    /**
     * sign the order info. 对订单信息进行签名
     *
     * @param content 待签名订单信息
     */
    private String sign(String content) {
        return SignUtils.sign(content, RSA_PRIVATE,true);
    }

    /**
     * get the sign type we use. 获取签名方式
     */
    private String getSignType() {
        return "sign_type=\"RSA\"";
    }

    /**
     * get the out_trade_no for an order. 生成商户订单号，该值在商户端应保持唯一（可自定义格式规范）
     */
    private String getOutTradeNo() {
        SimpleDateFormat format = new SimpleDateFormat("MMddHHmmss", Locale.getDefault());
        Date date = new Date();
        String key = format.format(date);

        Random r = new Random();
        key = key + r.nextInt();
        key = key.substring(0, 15);
        return key;
    }
    private class MyAdapter4 extends RecyclerView.Adapter<MyHolder4>{

        @NonNull
        @Override
        public MyHolder4 onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
            View view = LayoutInflater.from(dingdan.this).inflate(R.layout.item_dingdan,parent,false);
            MyHolder4 myHolder4= new MyHolder4(view);
            return myHolder4;
        }

        @Override
        public void onBindViewHolder(@NonNull MyHolder4 holder, int position) {
            holder.name.setText(list.get(position).getName());
            holder.des.setText(list.get(position).getDes());
            holder.num.setText(String.valueOf(list.get(position).getNum()));
            Glide.with(dingdan.this).load(String.valueOf(list.get(position).img)).into(holder.img);
        }

        @Override
        public int getItemCount() {
            return list.size();
        }
    }

    private class MyHolder4 extends RecyclerView.ViewHolder{

        ImageView img;
        TextView name,des,num;

        public MyHolder4(@NonNull View itemView) {
            super(itemView);
            img = itemView.findViewById(R.id.imageView15);
            name = itemView.findViewById(R.id.textView29);
            des = itemView.findViewById(R.id.textView10);
            num = itemView.findViewById(R.id.textView);
        }
    }
    private void init(){
        price1 = findViewById(R.id.price);
        back = findViewById(R.id.back);
        item = findViewById(R.id.recyclerView);
        address = findViewById(R.id.textView3);
        name = findViewById(R.id.textView4);
        tel = findViewById(R.id.textView5);
        submit = findViewById(R.id.constraintLayout);
    }
    public static String post(String url, String json) throws IOException {
        RequestBody body = RequestBody.create(MediaType.parse("application/json"), json);
        Request request = new Request.Builder()
                .url(url)
                .post(body)
                .build();
        Response response = BuyFragment.client.newCall(request).execute();
        if (response.isSuccessful()) {
            String res = response.body().string();
            Log.i("返回结果：", res);
            return res;
        } else {
            throw new IOException("Unexpected code " + response);
        }
    }

}